package com.example.aijie.autoreadhelper.utils;

import android.content.Context;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.text.TextUtils;
import android.view.Gravity;
import android.widget.Toast;

/**
 * 自定义Toast消息
 */
public class ToastHelper {

    private CharSequence mLastMessage;
    private long mLastTime;//上次弹出时间
    private final static long TIME_SHORT = 2_000L;//同样的消息弹出间隔

    private ToastHelper() {
    }

    /**
     * 显示Toast消息
     */
    private void showToast(Context context, CharSequence message, int gravity, int duration) {
        //不同内容，或大于2s后才能弹出
        if (TextUtils.equals(message, this.mLastMessage) && SystemClock.uptimeMillis() - mLastTime < TIME_SHORT) {
            return;
        }
        if (context == null || TextUtils.isEmpty(message)) {
            return;
        }

        Toast toast = Toast.makeText(context, message, duration == Toast.LENGTH_LONG ? duration : Toast.LENGTH_SHORT);
        if (gravity != Gravity.BOTTOM) {
            toast.setGravity(gravity, 0, 0);
        }
        toast.show();
        this.mLastMessage = message;
        this.mLastTime = SystemClock.uptimeMillis();
    }

    private void showToast(Context context, CharSequence message, int gravity) {
        showToast(context, message, gravity, Toast.LENGTH_SHORT);
    }

    private void showToast(Context context, CharSequence message) {
        showToast(context, message, Gravity.BOTTOM, Toast.LENGTH_SHORT);
    }

    private static ToastHelper toastHelper;

    private static ToastHelper getInstance() {
        if (toastHelper == null) {
            toastHelper = new ToastHelper();
        }
        return toastHelper;
    }

    public static void show(@NonNull Context context, CharSequence message) {
        getInstance().showToast(context, message);
    }

    public static void show(@NonNull Context context, @StringRes int id) {
        show(context, context.getString(id));
    }

    public static void showCenter(@NonNull Context context, CharSequence message) {
        getInstance().showToast(context, message, Gravity.CENTER);
    }

    public static void showCenter(@NonNull Context context, @StringRes int id) {
        showCenter(context, context.getString(id));
    }
}